package com.pfzy.lib.net.convert;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * CC转换器工厂
 */
public class CCConverterFactory extends Converter.Factory {
    private final Gson gson = new Gson();
    private final ResponseJsonParser mParser;

    public interface ResponseJsonParser {
        <T> T parse(String str, Type type);
    }

    public static CCConverterFactory create() {
        return create(null);
    }

    public static CCConverterFactory create(ResponseJsonParser parser) {
        return new CCConverterFactory(parser);
    }

    private CCConverterFactory(ResponseJsonParser parser) {
        this.mParser = parser;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        CCResponseConverter<Object> responseConverter = new CCResponseConverter<>(this.gson, type);
        responseConverter.setParser(this.mParser);
        return responseConverter;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = this.gson.getAdapter(TypeToken.get(type));
        return new CCRequestConverter(this.gson, adapter);
    }
}
